package com.steve.xfood.aspect;

import com.steve.xfood.constants.CookieConstant;
import com.steve.xfood.constants.RedisConstant;
import com.steve.xfood.exception.SellerAuthorizeException;
import com.steve.xfood.util.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * 通过AOP实现登录用户身份验证
 * @author steve
 * @date 2020/5/27 14:15
 */
@Aspect
@Component
@Slf4j
public class SellerAuthorizeAspect {
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 拦截的controller
     * 切点的意思：校验com.steve.xfood.controller下的所有Seller前缀的Controller，但排除掉SellerUserController（因为里面的登录和登出方法）
     */
    @Pointcut("execution(public * com.steve.xfood.controller.Seller*.*(..))" +
    "&& !execution(public * com.steve.xfood.controller.SellerUserController.*(..))")
    public void verify(){};

    /**
     * 在拦截controller之前执行的校验方法
     */
    @Before("verify()")
    public void doVerify() {
        //获取request
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //查询cookie
        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
        if (cookie == null) {
            log.warn("【微信登录】, Cookie查找不到token");
            //这里抛出的异常，会有SellerExceptionHandler进行捕获处理
            throw new SellerAuthorizeException();
        }

        //redis中查找cookie
        String tokenValue = redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));
        if (StringUtils.isEmpty(tokenValue)) {
            log.warn("【登录校验】, redis中查找不到token");
            throw new SellerAuthorizeException();
        }
    }
}
